<template>
    <el-row style="width: 100%;">
        <el-col :span="4">
            <el-button type="danger" style="height: 32px;width: 70px; line-height: 32px;" @click="handleBatchDelete()"
                :disabled="isdelete">
                <el-icon>
                    <DeleteFilled />
                </el-icon>
                &nbsp;删除
            </el-button>
            <el-button type="primary" style="height: 32px;width: 90px; line-height: 32px;" @click="handleAdd()">
                <el-icon>
                    <Plus />
                </el-icon>
                &nbsp;新增商品
            </el-button>
        </el-col>
        <el-col :span="3">
            <el-select v-model="search.category" style="width: 150px;height: 32px;" placeholder="类别">
                <el-option label="食品类" value='1' />
                <el-option label="服装类" value='2' />
                <el-option label="日用品类" value='3' />
                <el-option label="家具类" value='4' />
                <el-option label="家用电器类" value='5' />
                <el-option label="纺织品类" value='6' />
                <el-option label="五金电料类" value='7' />
                <el-option label="厨具类" value='8' />
            </el-select>
        </el-col>
        <el-col :span="6">
            <el-input v-model="input" style="width: 240px;height: 32px" placeholder="请输入搜索的内容" />
            <el-button type="primary" style="height: 32px;width: 65px; line-height: 32px;margin-left: 10px"
                @click="handleSearch()">
                <el-icon>
                    <Search />
                </el-icon>
                &nbsp;搜索
            </el-button>
        </el-col>
    </el-row>
    <el-row style="margin-top: 5px">
        <el-col :span="24">
            <el-table ref="multipleTableRef" :data="goodsData" style="width: 100%">
                <el-table-column type="selection" width="30" />
                <el-table-column label="序号" align="center" prop="index" width="60" />
                <el-table-column label="商品ID" align="center" prop="goods_id" width="" />
                <el-table-column label="商品名" align="center" prop="goods_name" width="140" />
                <el-table-column label="品牌" align="center" prop="brand" width="" />
                <el-table-column label="类别" align="center" width="110">
                    <template #default="scope">
                        <el-tag v-if="scope.row.category === '1'">食品类</el-tag>
                        <el-tag v-else-if="scope.row.category === '2'">服装类</el-tag>
                        <el-tag v-else-if="scope.row.category === '3'">日用品类</el-tag>
                        <el-tag v-else-if="scope.row.category === '4'">家具类</el-tag>
                        <el-tag v-else-if="scope.row.category === '5'">家用电器类</el-tag>
                        <el-tag v-else-if="scope.row.category === '6'">纺织品类</el-tag>
                        <el-tag v-else-if="scope.row.category === '7'">五金电料类</el-tag>
                        <el-tag v-else-if="scope.row.category === '8'">厨具类</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="销售商" align="center" prop="seller" />
                <el-table-column label="生产商" align="center" prop="manufacturer" width="" />
                <el-table-column label="发售日期" align="center" prop="release_date" width="120" />
                <el-table-column label="价格" align="center" prop="price" />
                <el-table-column label="库存量" align="center" prop="num" width="" />
                <el-table-column label="图片" align="center" width="100">
                    <template #default="scope">
                        <el-image :src="require('../assets/images/' + scope.row.imgurl)"
                            style="width: 100%; height: 100%"></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="按钮" align="center" width="160">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            修改
                        </el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                            <el-icon>
                                <DeleteFilled />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination background layout="prev, pager, next" :total="total" @current-change="currentChange"
                style="margin-left: 28%; margin-top: 10px " :default-page-size="5" />
        </el-col>
    </el-row>
    <GoodsDialog :dialogFormVisible :Goods="goods" :title="title" @update_dialogFormVisable="(newval) => {
        dialogFormVisible = false;
    }"></GoodsDialog>
</template>

<script lang="ts" setup>
import GoodsDialog from '../components/GoodsDialog.vue'
import { onMounted, ref, watchEffect } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus";
import { deleteGoodsApi, getGoodsListApi, searchGoodsApi } from '@/api/common';
import { ElTable } from 'element-plus'

const search = ref({
    category: '',
    massage: '',
})
const handleSearch = () => {
    searchGoodsApi(search.value).then((res) => {
        if (res.data.code === 200) {

            ElMessage.success("商品数据更新成功！")
        }
    }).catch((err) => {
        ElMessage.error("服务器错误！")
    })
}

interface Goods {
    index: number
    goods_id: number//商品id
    goods_name: string//商品名
    brand: string//品牌
    category: string//分类
    seller: string//销售商
    manufacturer: string//生产商
    release_date: Date//发售日期
    price: number//价格
    num: number//数量
    imgurl: string//图片地址
    description: string//描述
}
const goods = ref()
const title = ref()
var dialogFormVisible = ref(false);
const total = ref();
const input = ref('')
const handleDelete = (index: number, row: Goods) => {
    ElMessageBox.confirm("是否删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            deleteGoodsApi({

            }).then((res) => {
                if (res.data.code == 200) {
                    ElMessage({
                        type: "success",
                        message: "删除成功！",
                    });
                    getGoodsList();
                } else {
                    ElMessage.error("删除失败！")
                }
            }).catch((err) => {
                ElMessage.error("服务器错误！")
            })
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消删除！",
            });
        });
}
const tableData = ref([])
const goodsData = ref([])
const getGoodsList = () => {
    getGoodsListApi().then((res) => {
        tableData.value = res.data.data
        ElMessage.success("获取商品数据成功！")
        total.value = res.data.data.length
        getGoodsData(1)
    })
}
const currentChange = (val: number) => {
    getGoodsData(val);
}
const getGoodsData = (cur: number) => {
    goodsData.value = tableData.value.slice((cur - 1) * 5, cur * 5)
}
onMounted(() => {
    getGoodsList()
})

const handleEdit = (index: number, row: Goods) => {
    title.value = "修改商品信息"
    goods.value = row
    dialogFormVisible.value = true;
}
const handleAdd = () => {
    title.value = "新增商品信息"
    dialogFormVisible.value = true;
    goods.value = {
        goods_id: '',
        goods_name: '',
        brand: '',//品牌
        category: '',//分类
        seller: '',//销售商
        manufacturer: '',//生产商
        release_date: '',//发售日期
        price: '',//价格
        num: '',//数量
        imgurl: '',//图片地址
    };
}

// 添加selectedRows来存储选中的行
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const selectedRows = ref();
const isdelete = ref()
// 监听选中行的变化
watchEffect(() => {
    selectedRows.value = multipleTableRef.value?.getSelectionRows().map((row: any) => row.userid);
    isdelete.value = (selectedRows.value?.length === 0) ? true : false
});

// 批量删除方法
const handleBatchDelete = async () => {
    const confirmResult = await ElMessageBox.confirm(`确定删除选中的${selectedRows.value.length}项吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    });

    if (confirmResult === 'confirm') {
        try {
            // 假设后端API接受一个userid数组进行批量删除
            const response = await deleteGoodsApi({ book_id: selectedRows.value });
            if (response.data.code === 200) {
                ElMessage.success('批量删除成功！');
                // 删除后可以考虑刷新数据
                await getGoodsList();
            } else {
                ElMessage.error(response.data.message || '批量删除失败！');
            }
        } catch (err) {
            ElMessage.error('服务器错误！');
        }
    }
}
</script>

<style></style>